package net.wantongtech.xa.uploadbasicinfo.service;

import cn.com.taiji.sdk.comm.LwClientHelper;
import cn.com.taiji.sdk.model.comm.protocol.sdts.basics.issuer.*;
import cn.com.taiji.sdk.tools.JsonTools;
import com.google.common.collect.Sets;
import com.google.common.io.Files;
import com.wtkj.vo.dzzf.share.staticvalue.AgencyType;
import com.wtkj.vo.dzzf.share.staticvalue.ygz.OperationType;
import lombok.extern.slf4j.Slf4j;
import net.wantongtech.xa.uploadbasicinfo.constant.OrgStaticValue;
import net.wantongtech.xa.uploadbasicinfo.dao.UploadBasicInfoDao;
import net.wantongtech.xa.uploadbasicinfo.vo.Organization;
import org.apache.commons.lang.StringUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 上传基础信息服务实现
 *
 * @author MaShibo
 * 日期 :  2019/12/17
 */
@Slf4j
@Service
public class UploadBasicInfoService {


    /**
     * 默认到期日期
     */
    private static final String DEFAULT_END_TIME = "2999-12-12";

    /**
     * 默认启用日期
     */
    private static final String DEFAULT_START_TIME = "2017-12-31";

    @Resource
    private UploadBasicInfoDao uploadBasicInfoDao;


    public void upload() {

        List<Organization> organizationList = uploadBasicInfoDao.queryAllOrganization();
        if (organizationList.isEmpty()) {
            log.info("未查询到网点信息，结束执行");
            return;
        }

        log.info("共查询到{}条组织机构信息", organizationList.size());


        Set<String> channelIdSet = Sets.newHashSet();

        List<AgencyUploadRequest> agencyUploadRequestList = organizationList.stream()
                .filter(organization -> organization.getAgencyType() == AgencyType.AGENCY.getValue())
                .map(organization -> {
                    AgencyUploadRequest request = new AgencyUploadRequest();
                    request.setId(organization.getChannelId());
                    request.setName(StringUtils.deleteWhitespace(organization.getName()));
                    request.setContact(organization.getDirector());
                    request.setTel(organization.getOfficePhone());
                    request.setStartTime(DEFAULT_START_TIME);
                    request.setEndTime(DEFAULT_END_TIME);
                    request.setOperation(OperationType.ADD.getValue());
                    return request;
                }).collect(Collectors.toList());

        StringBuilder agencyError = new StringBuilder();
        agencyUploadRequestList.forEach(agencyUploadRequest -> {
            StringBuilder entryBuilder = new StringBuilder();
            String channelId = agencyUploadRequest.getId();
            if (!Pattern.matches(OrgStaticValue.NET_NAME_REGEX, agencyUploadRequest.getName())) {
                channelIdSet.add(channelId);
                entryBuilder.append(channelId).append(": 网点名称错误；");
            }
            if (!Pattern.matches(OrgStaticValue.CONTACT_REGEX, agencyUploadRequest.getContact())) {
                channelIdSet.add(channelId);
                entryBuilder.append(channelId).append(": 联系人错误；");
            }
            if (!Pattern.matches(OrgStaticValue.PHONE_REGEX, agencyUploadRequest.getTel())) {
                channelIdSet.add(channelId);
                entryBuilder.append(channelId).append("：联系方式错误；");
            }
            if (entryBuilder.length() > 0) {
                entryBuilder.append("\n");
                agencyError.append(entryBuilder);
            }
        });
        if (agencyError.length() > 0) {
            log.info("【客服合作机构上传及变更】错误信息：\n{}", agencyError);
        } else {
            agencyUploadRequestList.forEach(request -> {
                try {
                    uploadAgencyInfo(request);
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            });
        }


        List<HallUploadRequest> hallUploadRequestList = organizationList.stream()
                .filter(organization -> organization.getAgencyType() == AgencyType.SERVICEHALL.getValue())
                .map(organization -> {
                    HallUploadRequest request = new HallUploadRequest();
                    request.setId(organization.getChannelId());
                    request.setName(StringUtils.deleteWhitespace(organization.getName()));
                    request.setContact(organization.getDirector());
                    request.setTel(organization.getOfficePhone());
                    request.setAddress(organization.getAddress());
                    request.setServiceItems(OrgStaticValue.SERVICE_ITEMS);
                    request.setBusinessHours(OrgStaticValue.BUSINESS_HOURS);
                    request.setStartTime(DEFAULT_START_TIME);
                    request.setEndTime(DEFAULT_END_TIME);
                    request.setOperation(OperationType.ADD.getValue());
                    return request;
                }).collect(Collectors.toList());


        StringBuilder hallError = new StringBuilder();
        hallUploadRequestList.forEach(hallUploadRequest -> {
            StringBuilder entryBuilder = new StringBuilder();
            String channelId = hallUploadRequest.getId();
            if (!Pattern.matches(OrgStaticValue.NET_NAME_REGEX, hallUploadRequest.getName())) {
                channelIdSet.add(channelId);
                entryBuilder.append(channelId).append(": 网点名称错误；");
            }
            if (!Pattern.matches(OrgStaticValue.CONTACT_REGEX, hallUploadRequest.getContact())) {
                channelIdSet.add(channelId);
                entryBuilder.append(channelId).append(": 联系人错误；");
            }
            if (!Pattern.matches(OrgStaticValue.PHONE_REGEX, hallUploadRequest.getTel())) {
                channelIdSet.add(channelId);
                entryBuilder.append(channelId).append("：联系方式错误；");
            }
            if (!Pattern.matches(OrgStaticValue.NET_ADDRESS_REGEX, hallUploadRequest.getAddress())) {
                channelIdSet.add(channelId);
                entryBuilder.append(channelId).append("：地址错误；");
            }
            if (entryBuilder.length() > 0) {
                entryBuilder.append("\n");
                hallError.append(entryBuilder);
            }
        });
        if (hallError.length() > 0) {
            log.info("【服务网点信息上传及变更】错误信息：\n{}", hallError);
        }/* else {
            hallUploadRequestList.forEach(request -> {
                try {
                    uploadHallInfo(request);
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            });
        }*/

        try {
            String json = Files.toString(new File("C:\\Users\\MaShibo\\Desktop\\boc-hall.txt"), Charset.forName("UTF-8"));
            List<HallUploadRequest> requestList = JsonTools.json2List(json, HallUploadRequest.class);
            hallUploadRequestList.addAll(requestList);
            String text = JsonTools.toJsonStr(hallUploadRequestList);
            Files.write(text, new File("C:\\Users\\MaShibo\\Desktop\\upload.json"), Charset.forName("UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }


        List<MobileServiceUploadRequest> mobileServiceUploadRequests = organizationList.stream()
                .filter(organization -> organization.getAgencyType() == AgencyType.MOBILESERVICE.getValue())
                .map(organization -> {
                    MobileServiceUploadRequest request = new MobileServiceUploadRequest();
                    request.setId(organization.getChannelId());
                    request.setStartTime(DEFAULT_START_TIME);
                    request.setEndTime(DEFAULT_END_TIME);
                    request.setOperation(OperationType.ADD.getValue());
                    return request;
                }).collect(Collectors.toList());

        mobileServiceUploadRequests.forEach(request -> {
            try {
                uploadMobileServiceInfo(request);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        });


        List<TerminalUploadRequest> terminalUploadRequests = organizationList.stream()
                .filter(organization -> organization.getAgencyType() == AgencyType.TERMINAL.getValue())
                .map(organization -> {
                    TerminalUploadRequest request = new TerminalUploadRequest();
                    request.setId(organization.getChannelId());
                    request.setAddress(organization.getAddress());
                    request.setServiceItems(OrgStaticValue.SERVICE_ITEMS);
                    request.setBusinessHours(OrgStaticValue.BUSINESS_HOURS);
                    request.setStartTime(DEFAULT_START_TIME);
                    request.setEndTime(DEFAULT_END_TIME);
                    request.setOperation(OperationType.ADD.getValue());
                    return request;
                }).collect(Collectors.toList());
        StringBuilder terminalError = new StringBuilder();
        terminalUploadRequests.forEach(terminalUploadRequest -> {
            StringBuilder entryBuilder = new StringBuilder();
            String channelId = terminalUploadRequest.getId();
            if (!Pattern.matches(OrgStaticValue.NET_ADDRESS_REGEX, terminalUploadRequest.getAddress())) {
                channelIdSet.add(channelId);
                entryBuilder.append(channelId).append("：地址错误；");
            }
            if (entryBuilder.length() > 0) {
                entryBuilder.append("\n");
                terminalError.append(entryBuilder);
            }
        });

        if (terminalError.length() > 0) {
            log.info("【自助服务终端信息上传及变更】错误信息：\n{}", terminalError.toString());
        } else {
            terminalUploadRequests.forEach(request -> {
                try {
                    uploadTerminal(request);
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            });
        }


        List<OnlineUploadRequest> onlineUploadRequests = organizationList.stream()
                .filter(organization -> organization.getAgencyType() == AgencyType.ONLINE.getValue())
                .map(organization -> {
                    OnlineUploadRequest request = new OnlineUploadRequest();
                    request.setId(organization.getChannelId());
                    request.setName(StringUtils.deleteWhitespace(organization.getName()));
                    request.setServiceItems(OrgStaticValue.SERVICE_ITEMS);
                    request.setStartTime(DEFAULT_START_TIME);
                    request.setEndTime(DEFAULT_END_TIME);
                    request.setOperation(OperationType.ADD.getValue());
                    return request;
                }).collect(Collectors.toList());
        StringBuilder onlineError = new StringBuilder();
        onlineUploadRequests.forEach(onlineUploadRequest -> {
            StringBuilder entryBuilder = new StringBuilder();
            String channelId = onlineUploadRequest.getId();
            if (!Pattern.matches(OrgStaticValue.NET_NAME_REGEX, onlineUploadRequest.getName())) {
                channelIdSet.add(channelId);
                entryBuilder.append(channelId).append(": 网点名称错误；");
            }
            if (entryBuilder.length() > 0) {
                entryBuilder.append("\n");
                onlineError.append(entryBuilder);
            }
        });

        if (onlineError.length() > 0) {
            log.info("【线上服务渠道信息上传及变更】错误信息：\n{}", onlineError);
        } else {
            onlineUploadRequests.forEach(request -> {
                try {
                    uploadOnline(request);
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            });
        }

        if (!channelIdSet.isEmpty()) {
            log.info("出现错误信息的channelId为：{}", String.join(",",
                    channelIdSet.stream().map(channelId -> String.format("\'%s\'", channelId)).collect(Collectors.toSet())));
        }

    }


    private void uploadAgencyInfo(AgencyUploadRequest request) throws IOException {
        log.info("【客服合作机构上传及变更】请求：{}", request.toJson());
        AgencyUploadResponse response = LwClientHelper.binPostUrl(request);
        log.info("【客服合作机构上传及变更】响应：{}", response.toJson());
    }

    private void uploadHallInfo(HallUploadRequest request) throws IOException {
        log.info("【服务网点信息上传及变更】请求：{}", request.toJson());
        HallUploadResponse response = LwClientHelper.binPostUrl(request);
        log.info("【服务网点信息上传及变更】响应：{}", response.toJson());
    }

    private void uploadMobileServiceInfo(MobileServiceUploadRequest request) throws IOException {
        log.info("【流动服务网点信息上传及变更】请求：{}", request.toJson());
        MobileServiceUploadResponse response = LwClientHelper.binPostUrl(request);
        log.info("【流动服务网点信息上传及变更】响应：{}", response.toJson());
    }


    private void uploadTerminal(TerminalUploadRequest request) throws IOException {
        log.info("【自助服务终端信息上传及变更】请求：{}", request.toJson());
        TerminalUploadResponse response = LwClientHelper.binPostUrl(request);
        log.info("【自助服务终端信息上传及变更】响应：{}", response.toString());
    }


    private void uploadOnline(OnlineUploadRequest request) throws IOException {
        log.info("【线上服务渠道信息上传及变更】请求：{}", request.toJson());
        OnlineUploadResponse response = LwClientHelper.binPostUrl(request);
        log.info("【线上服务渠道信息上传及变更】响应：{}", response.toJson());
    }


    @SuppressWarnings("UnstableApiUsage")
    public void uploadByFile() {
        try {
            String json = Files.toString(new File("C:\\temp\\upload.json"), Charset.forName("UTF-8"));
            List<HallUploadRequest> requestList = JsonTools.json2List(json, HallUploadRequest.class);
            if (requestList.isEmpty()) {
                return;
            }
            requestList.forEach(request -> {
                try {
                    uploadHallInfo(request);
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            });
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }


}
